﻿using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Ekton_Manage_Web.Extensions.AuthMiddler
{
    public class PolicyHandler : AuthorizationHandler<PolicyRequirement>
    {
        private IApiSelectUserInfo _apiSelectUserInfo;//查前端用户
        private ISelectSysUser _selectSysUser;//查后端用户

        public PolicyHandler(IApiSelectUserInfo apiSelectUserInfo,
            ISelectSysUser selectSysUser)
        {
            _apiSelectUserInfo = apiSelectUserInfo;
            _selectSysUser = selectSysUser;
        }
        private static readonly object SingLock = new object();
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            lock (SingLock)
            {
                var http = (context.Resource as Microsoft.AspNetCore.Routing.RouteEndpoint);
                //是否经过验证
                var isAuthenticated = context.User.Identity.IsAuthenticated;
                if (isAuthenticated)
                {
                    //查看当前登陆人是前端还是后端
                    var claimInfo = context.User.Claims.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
                    var userInfo = JsonConvert.DeserializeObject<LoginUser>(claimInfo);
                    if (userInfo == null) return Task.CompletedTask;
                    if (userInfo.platform == "backstage")
                    {
                        var user = _selectSysUser.GetUser(Convert.ToInt32(userInfo.id)).Result;
                        if (user == null) return Task.CompletedTask;
                        if (user.state == 1) context.Succeed(requirement);
                    }
                    else
                    {
                        var user = _apiSelectUserInfo.GetUser(Convert.ToInt32(userInfo.id)).Result;
                        if (user == null) return Task.CompletedTask;
                        if (user.state == 1) context.Succeed(requirement);
                    }
                }
                return Task.CompletedTask;
            }
        }
    }
}
